package com.version.manager.controller.shop;

import com.version.manager.model.Msg;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
import java.util.UUID;

@RestController
@Api(value = "uploadController")
@RequestMapping("/api/shop/file")
public class uploadController {
    public static final String ROOT = "upload-dir";

    private final ResourceLoader resourceLoader;

    @Autowired
    public uploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    //显示图片
    @RequestMapping(method = RequestMethod.GET, value = "/image/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getFile(@PathVariable String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    //上传图片
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public Msg upload(MultipartFile file) throws IOException {

        String name=file.getOriginalFilename();
        name=name.substring(name.lastIndexOf("."));
        name=UUID.randomUUID().toString().replace("-","")+name;

        File dir = new File(ROOT);
        if(!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(Paths.get(ROOT, name));
        return Msg.success().addData(name);
    }
}
